package com.share.two.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;

/**
 *
 */
public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server>{

	@Override
	public void completed(AsynchronousSocketChannel asc, Server attachment) {
//		attachment.assc.accept(attachment, this);
//		read(asc);
		//当有下一个客户端接入的时候 直接使用Server的accept方法，这样反复下去，保证可以接收多个客户端
		attachment.assc.accept(attachment, this);
		read(asc);
	}

	private void read(final AsynchronousSocketChannel asc) {
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		//read方法是异步的，read读取完数据之后才会执行completed()方法
		asc.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
			@Override
			//result是client传过来数据的大小，attachment是client传过来的数据
			public void completed(Integer result, ByteBuffer attachment) {
				
				try {
					Thread.sleep(1000);
					System.out.println("server:  completed()方法");
				} catch (Exception e) {
					// TODO: handle exception
				}
				attachment.flip();
				System.out.println("server:  接收" + new String(attachment.array(), 0, attachment.remaining()));
				write(asc, "server收到");
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				exc.printStackTrace();
				
			}
		});
		
		System.out.println("server:  read()主线程");
		
	}
	
	
	public void write(AsynchronousSocketChannel asc, String string){
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put(string.getBytes());
		buffer.flip();
		try {
//			Future<Integer> write = asc.write(buffer);
			asc.write(buffer).get();
			buffer.flip();
			System.out.println("server:  返回" + new String(buffer.array(), 0, buffer.remaining()));
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}

	@Override
	public void failed(Throwable exc, Server attachment) {
		exc.printStackTrace();
		
	}

}
